package com.hcx.base.thread;

/**
 * 死锁模拟
 */
public class ThreadLockDemo implements Runnable {

    /*
     锁对象唯一
      */
    Object object1 = new Object();
    Object object2 = new Object();

    public void run() {
        String name = Thread.currentThread().getName();
        String s1 = "线程A";
        String s2 = "线程B";

        if (name.equals(s1)) {
            synchronized (object1) {
                System.out.println("线程A拿到了A锁");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (object2) {
                    System.out.println("线程A拿到了B锁");
                }
            }
        }
        if (name.equals(s2)) {
            synchronized (object2) {
                System.out.println("线程B拿到了B锁");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (object1) {
                    System.out.println("线程B拿到了A锁");
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadLockDemo demo = new ThreadLockDemo();
        Thread threadA = new Thread(demo, "线程A");
        Thread threadB = new Thread(demo, "线程B");
        threadA.start();
        ;
        threadB.start();
        threadA.join();
        System.out.println("我执行完成了");
    }

}
